import { Component, OnInit, Output, EventEmitter, Input, ViewChild, TemplateRef, HostBinding } from '@angular/core';
import { TreeNode, TreeTableComponent } from '@farris/ui-treetable';
import { NotifyService } from '@farris/ui-notify';
import { DesignViewModelService } from '@farris/designer-services';


/**
 * 列表、树表的列选择器：生成字段bindingPath的数组或字符串
 */
@Component({
  selector: 'app-group-field-editor',
  templateUrl: './group-field-editor.component.html',
  styleUrls: ['./group-field-editor.component.css']
})
export class GroupFieldEditorComponent implements OnInit {
  @Output() closeModal = new EventEmitter<any>();
  @Output() submitModal = new EventEmitter<any>();
  @Input() value;
  @Input() editorParams: any = { viewModelId: '', selectNumber: null, resultType: 'array' };
  @ViewChild('gridFieldFooter') modalFooter: TemplateRef<any>;
  modalConfig = {
    title: '列选择器',
    width: 900,
    height: 500,
    showButtons: true
  };

  @ViewChild('tt') sourceTree: TreeTableComponent;
  idField = 'id';
  @HostBinding('class')
  cls = 'h-100 d-flex flex-column p-2 flex-fill';

  // 左侧选中的列
  get leftCheckeds() {
    if (this.sourceTree.selections) {
      return this.sourceTree.selections.map(n => {
        return n.data;
      });
    } else {
      return [];
    }
  }

  // 右侧显示列
  selectedColumns = [];

  // 右侧选中的列
  rightCheckeds: any = {};

  // 左侧树
  sourceColumnsTreeData: TreeNode[] = [];

  // 打平关联字段后的列数据
  plainColumns: TreeNode[] = [];


  constructor(
    private dgVMService: DesignViewModelService, private notifyService: NotifyService) { }

  ngOnInit(): void {
    if (!this.editorParams) {
      return;
    }
    this.sourceColumnsTreeData = this.dgVMService.getAllFields2TreeByVMId(this.editorParams.viewModelId);

    this.getSelectedColumns();
  }

  /**
   * 获取已选择的列
   */
  getSelectedColumns() {
    if (!this.value) {
      return [];
    }
    let fieldArray = [];
    if (this.editorParams.resultType === 'string') {
      fieldArray = this.value.split(',');
    } else {
      fieldArray = this.value;
    }

    this.plainColumns = this.convertTreeNodes2PlainObject(this.sourceColumnsTreeData);
    fieldArray.forEach(value => {
      const element = this.plainColumns.find(e => e.data.bindingPath === value);
      if (element) {
        this.selectedColumns.push(element.data);
      }
    });


  }

  isChecked(col: any, direction: string): boolean {
    if (direction === 'l') {
      return this.leftCheckeds[col['id']] !== undefined;
    } else {
      return this.rightCheckeds[col['id']] !== undefined;
    }
  }

  /**
   * 字段是否可勾选
   * 1、已选字段不可勾选
   * 2、主表的udt字段、关联字段不可勾选
   * @param col
   */
  canChecked(col) {
    if (col.type && col.type.fields && col.type.fields.length > 0) {
      return false;
    }
    if (this.selectedColumns.length === 0) {
      return true;
    }
    if (this.selectedColumns.findIndex(c => c['id'] === col['id']) === -1) {
      return true;
    }


  }



  hasCheckeds(side: string) {
    if (side === 'l') {
      return this.leftCheckeds.length > 0;
    } else {
      return Object.keys(this.rightCheckeds).length > 0;
    }
  }

  rightColumnChecked(col) {
    if (this.isChecked(col, 'r')) {
      this.rightCheckeds = {};
      return;
    } else {
      this.rightCheckeds = {};
      this.rightCheckeds[col['id']] = col;
    }
  }

  //#region 左右移动

  /** 右移 */
  // 1：若右边已有选中的分组列，如何处理，覆盖？还是提示先将右边的移到左边再进行操作？
  moveToRight() {
    if (!this.hasCheckeds('l')) {
      this.notifyService.warning('请选择要移动的列。');
      return;
    }

    if (this.editorParams.selectNumber && this.leftCheckeds.length > this.editorParams.selectNumber) {
      this.notifyService.warning('最多允许选择' + this.editorParams.selectNumber + '列！');
      return;
    }

    if (this.editorParams.selectNumber && this.selectedColumns.length + this.leftCheckeds.length > this.editorParams.selectNumber) {
      this.notifyService.warning('最多允许选择' + this.editorParams.selectNumber + '列，请先移除部分已选列！');
      return;
    }
    // this.selectedColumns = [];
    this.leftCheckeds.forEach(col => {
      if (this.selectedColumns.indexOf(col) === -1) {
        this.selectedColumns.push(col);
      }
    });
    this.clearSelections();
  }

  private clearSelections() {
    this.sourceTree.selectedRow = undefined;
    this.sourceTree.clearAll();
  }

  /** 左移 */
  moveToLeft() {
    if (!this.hasCheckeds('r')) {
      this.notifyService.warning('请选择要取消的列。');
      return;
    }
    if (this.hasCheckeds('r')) {
      this.selectedColumns = this.selectedColumns.filter(v => {
        return Object.values(this.rightCheckeds).indexOf(v) === -1;
      });

      this.rightCheckeds = {};
    }
  }


  private convertTreeNodes2PlainObject(nodes: TreeNode[], r: any[] = []): TreeNode[] {
    if (nodes) {
      nodes.forEach(n => {
        r.push(n);
        if (n.children) {
          this.convertTreeNodes2PlainObject(n.children, r);
        }
      });
    }

    return r;
  }

  getTreeNodeByID(fieldId: string) {
    return this.plainColumns.find(column => column.data.id === fieldId);
  }
  /**
   * 确定
   */
  clickConfirm() {
    const tmp = [];

    for (const col of this.selectedColumns) {
      if (col.bindingPath) {
        tmp.push(col.bindingPath);
      } else {
        this.notifyService.error('选定的字段没有bindingPath属性，请先更新表单schema再选择列。');
        return;
      }
    }

    // 区分返回的数据类型
    if (this.editorParams.resultType === 'string') {
      this.submitModal.emit({ value: tmp.toString() });
    } else {
      this.submitModal.emit({ value: tmp });
    }
  }


  /**
   * 取消
   */
  clickCancel() {
    this.closeModal.emit();
  }

}
